package com.wr.ForkJoinDemo11;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//         test1();  //用时4748
         test2();  //用时6364
//         test3();  //用时347
    }


    public static void test1(){
        long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间："+(end-start));

    }

    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinDemo11 = new ForkJoinDemo11(1L, 10_0000_0000L);
//        forkJoinPool.execute(forkJoinDemo11);  // execute异步执行  没有返回结果

//        ForkJoinTask<Long> joinTask = forkJoinPool.submit(forkJoinDemo11);// submit异步执行  有返回结果Task 可通过task.get 实现同步到主线程
//        Long sum = joinTask.get();
        Long sum = forkJoinPool.invoke(forkJoinDemo11);// invoke  返回泛型结果  invoke(ForkJoinTask) 有Join, tasks会被同步到主进程
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间："+(end-start));

    }


    // 流式并行计算
    public static void test3(){
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间："+(end-start));

    }
}
